<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form ref="formSearch" :inline="true" :model="queryData">
				<el-form-item
					:label="$t('common.belong_merchant') + ':'"
					prop="merchantId"
				>
					<merchant-select
						v-model="queryData.merchantId"
					></merchant-select>
				</el-form-item>
				<el-form-item>
					<el-select
						v-model="queryData.queryDateTypeId"
						size="medium"
						style="width:120px"
					>
						<el-option
							:label="$t('agent.operation_time')"
							:value="1"
						></el-option>
						<el-option
							:label="$t('common.createAt')"
							:value="2"
						></el-option>
					</el-select>
					<el-date-picker
						v-model="searchTime"
						size="medium"
						:clearable="true"
						:picker-options="pickerShortcut2"
						format="yyyy-MM-dd HH:mm:ss"
						type="datetimerange"
						range-separator="-"
						:start-placeholder="$t('common.start_date')"
						:end-placeholder="$t('common.end_date')"
						:default-time="defaultTime"
					></el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-select
						v-model="selectSearchType"
						style="width: 120px"
						:placeholder="$t('common.please_choose')"
					>
						<el-option
							:label="$t('agent.exclusive_domain')"
							:value="1"
						></el-option>
						<el-option
							:label="$t('agent.bind_agent')"
							:value="2"
						></el-option>
						<el-option
							:label="$t('common.updateBy')"
							:value="3"
						></el-option>
					</el-select>
					<el-input
						v-model.trim="selectSearchVal"
						clearable
						size="medium"
						style="width: 200px"
						:placeholder="$t('common.please_enter')"
					></el-input>
				</el-form-item>
				<el-form-item :label="$t('agent.bind_status') + ':'">
					<el-select
						v-model="queryData.bindingStatus"
						size="medium"
						clearable
						:placeholder="$t('common.all')"
						style="width: 120px"
					>
						<el-option
							v-for="item in domainBindStatusArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('agent.domain_status') + ':'">
					<el-select
						v-model="queryData.domainStatus"
						size="medium"
						clearable
						:placeholder="$t('common.all')"
						style="width: 120px"
					>
						<el-option
							v-for="item in domainStatusArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						:loading="loading"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						:disabled="loading"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('203021')"
						type="warning"
						icon="el-icon-plus"
						:disabled="loading"
						size="medium"
						@click="addAndEdit(1)"
					>
						{{ $t('agent.add') }}
					</el-button>
					<el-button
						v-if="hasPermission('203022')"
						type="success"
						icon="el-icon-folder"
						:disabled="loading"
						size="medium"
						@click="importData()"
					>
						{{ $t('agent.import') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				class="small-size-table"
				:data="dataList"
				style="width: 100%"
				:max-height="tableHeight"
				:header-cell-style="getRowClass"
				highlight-current-row
			>
				<el-table-column
					prop="merchantId"
					align="center"
					:label="$t('common.belong_merchant')"
				>
					<template slot-scope="scope">
						<span v-if="!!scope.row.merchantId">
							<span>
								{{ merchantFilter(scope.row.merchantId) }}
							</span>
						</span>
						<span v-else>-</span>
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					:label="$t('agent.exclusive_domain')"
					prop="exclusiveDomainName"
				></el-table-column>

				<el-table-column
					align="center"
					:label="$t('agent.domain_status')"
					prop="domainStatus"
					width="90"
				>
					<template slot-scope="scope">
						<div
							:class="
								scope.row.domainStatus === 1
									? 'normalRgba'
									: 'disableRgba'
							"
						>
							{{ filterDomainStatus(scope.row.domainStatus) }}
						</div>
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					:label="$t('agent.bind_status')"
					prop="bindingStatus"
					:width="getWidth(90, 1.5)"
				>
					<template slot-scope="scope">
						<div
							:class="
								scope.row.bindingStatus === 1
									? 'normalRgba'
									: 'disableRgba'
							"
						>
							{{ filterBindStatus(scope.row.bindingStatus) }}
						</div>
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					:label="$t('agent.bind_agent')"
					prop="bindProxy"
					width="90"
				>
					<template slot-scope="scope">
						{{ scope.row.bindProxy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					:label="$t('agent.description')"
					prop="domainDesc"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.domainDesc || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					:label="$t('common.createBy')"
					prop="createdBy"
					width="90"
				></el-table-column>
				<el-table-column
					align="center"
					:label="$t('common.createAt')"
					prop="createdAt"
				></el-table-column>
				<el-table-column
					align="center"
					:label="$t('common.last_updateBy')"
					prop="updatedBy"
					width="100"
				></el-table-column>
				<el-table-column
					align="center"
					:label="$t('common.last_updateAt')"
					width="110"
					prop="updatedAt"
				></el-table-column>
				<el-table-column
					align="center"
					:label="$t('common.actions')"
					width="320"
					fixed="right"
				>
					<template slot-scope="scope">
						<el-button
							v-if="hasPermission('203023')"
							:type="
								scope.row.domainStatus === 1
									? 'danger'
									: 'success'
							"
							:icon="
								scope.row.domainStatus === 1
									? 'el-icon-open'
									: 'el-icon-turn-off'
							"
							size="medium"
							@click.stop="
								operationTips(scope.row.domainStatus, scope.row)
							"
						>
							{{
								scope.row.domainStatus === 1
									? $t('agent.disable')
									: $t('common.start_up')
							}}
						</el-button>
						<el-button
							v-if="hasPermission('203024')"
							:type="
								scope.row.bindingStatus === 1
									? 'danger'
									: 'success'
							"
							:icon="
								scope.row.bindingStatus === 1
									? 'el-icon-unlock'
									: 'el-icon-lock'
							"
							size="medium"
							@click.stop="
								scope.row.bindingStatus !== 1
									? addAndEdit(2, scope.row)
									: operationTips(3, scope.row)
							"
						>
							{{
								scope.row.bindingStatus === 1
									? $t('agent.unbund')
									: $t('agent.bind')
							}}
						</el-button>
						<el-button
							v-if="hasPermission('203028')"
							type="primary"
							icon="el-icon-edit"
							size="medium"
							@click.stop="addAndEdit(3, scope.row)"
						>
							{{ $t('common.edit') }}
						</el-button>
						<el-button
							v-if="hasPermission('203025')"
							type="warning"
							icon="el-icon-delete"
							size="medium"
							:disabled="
								scope.row.domainStatus === 1 ||
									scope.row.bindingStatus === 1
							"
							@click="operationTips(4, scope.row)"
						>
							{{ $t('common.delete') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				:current-page.sync="pageNum"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<el-dialog
			:visible.sync="dialogVisible"
			:title="dialogTitle"
			width="500px"
			center
			:destroy-on-close="true"
			:show-close="false"
			class="addBox"
		>
			<el-form
				v-if="isDisabled !== 3"
				ref="add"
				:model="addOrEditData"
				label-width="auto"
			>
				<el-form-item
					:label="$t('agent.exclusive_domain') + ':'"
					prop="exclusiveDomainName"
					:rules="[
						{
							required: true,
							message: $t('agent.rule_input_tip_domain'),
							trigger: 'blur'
						}
					]"
				>
					<el-input
						v-model.trim="addOrEditData.exclusiveDomainName"
						:placeholder="$t('agent.rule_input_tip_domain')"
						clearable
						:disabled="isDisabled === 2"
						maxlength="500"
					></el-input>
				</el-form-item>
				<el-form-item
					v-if="isDisabled === 1"
					:label="$t('agent.bind_agent') + ':'"
					prop="bindProxy"
					:rules="[
						{
							required: true,
							message: $t('agent.rule_input_tip_account'),
							trigger: 'blur'
						}
					]"
				>
					<el-input
						v-input="{ name: 'symbols' }"
						v-model="addOrEditData.bindProxy"
						:placeholder="$t('agent.rule_input_tip_account')"
						clearable
						show-word-limit
						maxlength="12"
					></el-input>
				</el-form-item>
				<el-form-item
					v-else
					:label="$t('agent.bind_agent') + ':'"
					prop="bindProxy"
					:rules="[
						{
							required: true,
							validator: bindProxyVlidate,
							trigger: 'blur'
						}
					]"
				>
					<el-input
						v-input="{ name: 'symbols' }"
						v-model="addOrEditData.bindProxy"
						:placeholder="$t('agent.rule_input_tip_account')"
						clearable
						show-word-limit
						maxlength="12"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="$t('common.belong_merchant') + ':'"
					prop="merchantId"
					:rules="[
						{
							required: true,
							message: $t('agent.rule_select_tip_merchant'),
							trigger: 'blur'
						}
					]"
				>
					<merchant-select
						v-model="addOrEditData.merchantId"
						:placeholder="$t('common.please_choose')"
					></merchant-select>
				</el-form-item>
				<el-form-item :label="$t('agent.description_info') + ':'">
					<el-input
						v-model.trim="addOrEditData.domainDesc"
						type="textarea"
						:placeholder="$t('common.please_enter')"
						maxlength="500"
						show-word-limit
					></el-input>
				</el-form-item>
			</el-form>
			<el-form
				v-else
				ref="Edit"
				:model="addOrEditData"
				label-width="auto"
			>
				<el-form-item
					:label="$t('agent.description_info') + ':'"
					prop="domainDesc"
					:rules="[
						{
							required: true,
							message: $t('common.please_enter'),
							trigger: 'blur'
						}
					]"
				>
					<el-input
						v-model.trim="addOrEditData.domainDesc"
						type="textarea"
						:placeholder="$t('common.please_enter')"
						maxlength="500"
						show-word-limit
					></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">
					{{ $t('agent.cancel') }}
				</el-button>
				<el-button type="primary" @click="save">
					{{ $t('common.sure') }}
				</el-button>
			</span>
		</el-dialog>
		<uploadFile
			:uploadVisible.sync="uploadVisible"
			@load-data="search"
		></uploadFile>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import uploadFile from './components/uploadFile.vue'
import { filterEmptyParams } from '@/utils'
import MainContent from '@/components/MainContent/index.vue'
const end = () =>
	dayjs()
		.endOf('day')
		.valueOf()
const start = () =>
	dayjs()
		.startOf('day')
		.valueOf()
export default {
	name: 'ExclusiveDomain',
	components: { uploadFile, MainContent },
	mixins: [list],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			queryData: { queryDateTypeId: 2 },
			searchTime: [start(), end()],
			selectSearchVal: '',
			selectSearchType: 1,
			dataList: [],
			dialogVisible: false,
			dialogTitle: '',
			uploadVisible: false,
			addOrEditData: {},
			isDisabled: true,
			control: true
		}
	},
	computed: {
		domainBindStatusArr() {
			return this.globalDics.exclusiveBind || []
		},
		domainStatusArr() {
			return this.globalDics.exclusiveDomain || []
		},
		appIdArr() {
			return this.globalDics.appId || []
		},
		accountTypeArr() {
			return this.globalDics.accountType || []
		}
	},
	methods: {
		loadData() {
			this.loading = true
			delete this.queryData.exclusiveDomainName
			delete this.queryData.bindProxy
			delete this.queryData.updatedBy
			if (this.selectSearchType === 1) {
				this.queryData.exclusiveDomainName = this.selectSearchVal
			} else if (this.selectSearchType === 2) {
				this.queryData.bindProxy = this.selectSearchVal
			} else if (this.selectSearchType === 3) {
				this.queryData.updatedBy = this.selectSearchVal
			}

			const timeArr = this.searchTime || []
			const [start, end] = timeArr
			const params = {
				startTime: start
					? dayjs(start).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				endTime: end
					? dayjs(end).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				...this.getParams(this.queryData)
			}
			this.$api
				.getExclusiveDomainDomainList(filterEmptyParams(params))
				.then((res) => {
					const { record, totalRecord } = res.data || {}
					this.dataList = Array.isArray(record)
						? Object.freeze(record)
						: []
					this.total = totalRecord || 0
					this.loading = false
				})
				.catch(() => (this.loading = false))
		},
		addAndEdit(type, data) {
			this.isDisabled = type
			this.addOrEditData = {}
			const {
				id,
				exclusiveDomainName,
				bindProxy,
				domainDesc,
				appId,
				merchantId
			} = {
				...data
			}
			this.addOrEditData = {
				id,
				exclusiveDomainName,
				bindProxy,
				domainDesc,
				appId,
				merchantId
			}
			this.dialogVisible = true
			this.dialogTitle = this.$t('common.create')
			if (type === 2) {
				this.dialogTitle = ''
				this.addOrEditData.bindingStatus = 1
			} else if (type === 3) {
				this.dialogTitle = this.$t('common.edit')
				this.$nextTick(() => {
					this.$refs.Edit.clearValidate()
					this.control = false
				})
			} else {
				this.$nextTick(() => {
					this.$refs.add.clearValidate()
					this.control = true
				})
			}
		},
		filterBindStatus(code) {
			const o = this.domainBindStatusArr.find(
				(item) => parseFloat(item.code) === parseFloat(code)
			)
			if (o) {
				return o.description
			}
		},
		filterDomainStatus(code) {
			const o = this.domainStatusArr.find(
				(item) => parseFloat(item.code) === parseFloat(code)
			)
			if (o) {
				return o.description
			}
		},
		importData() {
			this.uploadVisible = !this.uploadVisible
		},
		save() {
			const ele = this.isDisabled === 3 ? 'Edit' : 'add'
			const text =
				this.isDisabled === 2
					? this.$t('agent.bind_success')
					: this.isDisabled === 3
					? this.$t('common.edit_success')
					: this.$t('common.add_success')
			const httpStr =
				this.isDisabled === 2
					? 'setExclusiveDomainUpdateBind'
					: 'setExclusiveDomainSaveDomain'
			this.$refs[ele].validate((valid) => {
				if (valid) {
					const loading = this.$loading({
						lock: true,
						text: '',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					})
					this.$api[httpStr](this.addOrEditData)
						.then(() => {
							this.dialogVisible = false
							this.$message.success(text)
							loading.close()
							this.loadData()
						})
						.catch(() => {
							loading.close()
						})
				}
			})
		},
		operationTips(flag, val) {
			let str = ''
			const obj = {
				id: val.id,
				status: undefined
			}
			let httpStr = ''
			let msgText = ''
			switch (flag) {
				case 1:
					obj.status = 2
					msgText = this.$t('agent.stop_success')
					httpStr = 'setExclusiveDomainUse'
					str = `<strong>${this.$t(
						'agent.is_stop_domain'
					)}?</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
						'agent.rule_careful_tip2'
					)}!</span>`
					break
				case 2:
					obj.status = 1
					msgText = this.$t('agent.enabled_success')
					httpStr = 'setExclusiveDomainUse'
					str = `<strong>${this.$t(
						'agent.is_enable_domain'
					)}?</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
						'agent.rule_careful_tip3'
					)}!</span>`
					break
				case 3:
					obj.bindingStatus = 2
					msgText = this.$t('agent.unbund_success')
					httpStr = 'setExclusiveDomainUpdateBind'
					str = `<strong>${this.$t(
						'agent.is_unbind_config'
					)}</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
						'agent.rule_careful_tip'
					)}</span>`
					break
				case 4:
					msgText = this.$t('agent.delete_success')
					httpStr = 'setExclusiveDomainDeleteDomain'
					str = `<strong>${this.$t(
						'agent.is_delete_domain'
					)}?</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
						'agent.rule_careful_tip'
					)}</span>`
					break
				default:
					break
			}
			this.$confirm(str, this.$t('common.success_tip'), {
				dangerouslyUseHTMLString: true,
				confirmButtonText: this.$t('common.confirm'),
				cancelButtonText: this.$t('common.cancel'),
				type: 'warning'
			})
				.then(() => {
					const loading = this.$loading({
						lock: true,
						text: '',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					})
					if (httpStr) {
						this.$api[httpStr](obj)
							.then(() => {
								this.$message.success(msgText)
								loading.close()
								this.loadData()
							})
							.catch(() => loading.close())
					} else {
						loading.close()
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		reset() {
			this.pageNum = 1
			this.selectSearchVal = ''
			this.selectSearchType = 1
			this.queryData = {
				queryDateTypeId: 2
			}
			this.searchTime = [start(), end()]
			this.loadData()
		},
		bindProxyVlidate(rule, value, callback) {
			const reg = /[0-9 A-Z a-z]$/
			if (reg.test(value)) {
				callback()
			} else {
				callback(this.$t('agent.rule_input_tip_account'))
			}
		},
		_changeTableSort({ column, prop, order }) {
			const obj = {
				updatedAt: 1,
				createdAt: 2
			}
			this.queryData.orderKey = obj[prop]
			if (order === 'ascending') {
				// 升序
				this.queryData.orderType = 'asc'
			} else if (column.order === 'descending') {
				// 降序
				this.queryData.orderType = 'desc'
			} else {
				delete this.queryData.orderKey
				delete this.queryData.orderType
			}
			this.loadData()
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-input-group__prepend {
	background-color: #fff;
}
</style>
